﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace PlutoStudio
{
    /// <summary>
    /// 对象扩展方法类
    /// </summary>
    public static class ObjectExtensions
    {
        /// <summary>
        ///     把对象类型转化为指定类型，转化失败时返回该类型默认值
        /// </summary>
        /// <typeparam name="T"> 动态类型 </typeparam>
        /// <param name="value"> 要转化的源对象 </param>
        /// <returns> 转化后的指定类型的对象，转化失败返回类型的默认值 </returns>
        public static T CastTo<T>(this object value)
        {
            object result;
            Type type = typeof(T);
            try
            {
                if (type.IsEnum)
                {
                    result = Enum.Parse(type, value.ToString());
                }
                else if (type == typeof(Guid))
                {
                    result = Guid.Parse(value.ToString());
                }
                else
                {
                    result = Convert.ChangeType(value, type);
                }
            }
            catch
            {
                result = default(T);
            }

            return (T)result;
        }

        /// <summary>
        ///     把对象类型转化为指定类型，转化失败时返回指定的默认值
        /// </summary>
        /// <typeparam name="T"> 动态类型 </typeparam>
        /// <param name="value"> 要转化的源对象 </param>
        /// <param name="defaultValue"> 转化失败返回的指定默认值 </param>
        /// <returns> 转化后的指定类型对象，转化失败时返回指定的默认值 </returns>
        public static T CastTo<T>(this object value, T defaultValue)
        {
            object result;
            Type type = typeof(T);
            try
            {
                result = type.IsEnum ? Enum.Parse(type, value.ToString()) : Convert.ChangeType(value, type);
            }
            catch
            {
                result = defaultValue;
            }
            return (T)result;
        }

        /// <summary>
        /// 创建指定类型的新实例。 
        /// </summary>
        /// <typeparam name="T">需要实例化的对象类型</typeparam>
        /// <param name="appDomain">对象所在的应用程序域</param>
        /// <returns>指定类型的实例</returns>
        public static T CreateInstanceAndUnwrap<T>(this AppDomain appDomain)
        {
            var type = typeof(T);
            var result = (T)appDomain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
            return result;
        }

        /// <summary>
        /// 将指定的对象序列化成Xml文档。
        /// </summary>
        /// <param name="value">要序列化的对象</param>
        /// <returns>生成的Xml文档</returns>
        public static string ToXml(this object value)
        {
            var result = new StringBuilder();
            using (var stream = XmlWriter.Create(result,new XmlWriterSettings { Encoding = Encoding.UTF8 }))
            {
                stream.WriteProcessingInstruction("xml", @"version=""1.0"" encoding=""utf-8""");
                System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(value.GetType());
                xml.Serialize(stream, value);
            }
            return result.ToString();
        }

        /// <summary>
        /// 将指定的对象转换成键值对。
        /// </summary>
        /// <param name="value">要转换的对象</param>
        /// <returns>生成的键值对</returns>
        public static IDictionary<string, object> ToDictionary(this object value)
        {
            return new RouteValueDictionary(value);
        }

        /// <summary>
        /// 将指定的对象转换成键值对。
        /// </summary>
        /// <param name="value">要转换的对象</param>
        /// <param name="useDescription">是否使用<see cref="DescriptionAttribute"/>作为<see cref="IDictionary{TKey, TValue}"/>的键。</param>
        /// <returns>生成的键值对</returns>
        public static IDictionary<string, object> ToDictionary(this object value,bool useDescription)
        {
            return new RouteValueDictionary(value,useDescription);
        }


        /// <summary>
        /// 从类型成员获取指定Attribute特性
        /// </summary>
        /// <typeparam name="T">Attribute特性类型</typeparam>
        /// <param name="value">类型类型成员</param>
        /// <param name="inherit">是否从继承中查找</param>
        /// <returns>存在返回第一个，不存在返回null</returns>
        public static T GetAttribute<T>(this object value, bool inherit) where T : Attribute
        {
            var type = value.GetType();
            return type.GetCustomAttributes(typeof(T), inherit).SingleOrDefault() as T;
        }



        /// <summary>
        /// 将指定的Xml文档反序列化成指定类型的对象。
        /// </summary>
        /// <typeparam name="T">对象的类型</typeparam>
        /// <param name="xml">要反序列化的Xml文档</param>
        /// <returns>反序列化生成的对象</returns>
        public static T FromXml<T>(this string xml)
        {
            using (var stream = new StringReader(xml))
            {
                System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                return (T)xmlSerializer.Deserialize(stream);
            }
        }
    }

    /// <summary>
    /// Json序列化及反序列化扩展方法类
    /// </summary>
    public static class JsonExtensions
    {
        /// <summary>
        /// 将JSON字符串反序列化成指定类型的对象。
        /// </summary>
        /// <typeparam name="T">对象的类型</typeparam>
        /// <param name="value">要反序列化的JSON字符串</param>
        /// <returns>反序列化生成的对象</returns>
        public static T Deserialize<T>(this string value)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
        }

        /// <summary>
        /// 将JSON字符串反序列化成Object对象。
        /// </summary>
        /// <param name="value">要反序列化的JSON字符串</param>
        /// <returns>反序列化生成的对象</returns>
        public static object Deserialize(this string value)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject(value);
        }

        /// <summary>
        /// 将JSON字符串反序列化成指定类型的对象。
        /// </summary>
        /// <param name="value">要反序列化的JSON字符串</param>
        /// <param name="type">对象的类型</param>
        /// <returns>反序列化生成的对象</returns>
        public static object Deserialize(this string value, Type type)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject(value, type);
        }

        /// <summary>
        /// 将指定的对象序列化成JSON字符串。
        /// </summary>
        /// <param name="value">要序列化的对象</param>
        /// <returns>生成的JSON字符串</returns>
        public static string Serialize(this object value)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(value);
        }

    }
}
